<template>
    <div class="add-exam-component-box">
      <div class="add-exam-component">
        <!-- 竞赛信息模块 -->
        <div class="exam-base-info-box">
          <!-- 标题 -->
          <div class="exam-base-title">
            <span class="base-title">{{ type === 'edit' ? '编辑竞赛' : '添加竞赛' }}</span>
            <span class="go-back" @click="goBack">返回</span>
          </div>
          <!-- 基本信息 -->
          <div class="exam-base-info">
            <div class="group-box">
              <div class="group-item">
                <div class="item-label required">竞赛名称</div>
                <div>
                  <el-input v-model="formExam.title" style="width:420px" placeholder="请填写竞赛名称"></el-input>
                </div>
              </div>
            </div>
            <div class="group-box">
              <div class="group-item">
                <div class="item-label required">竞赛周期</div>
                <div>
                  <el-date-picker v-model="formExam.examDate" :disabledDate="disabledDate" type="datetimerange"
                    start-placeholder="竞赛开始时间" end-placeholder="竞赛结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
                </div>
              </div>
            </div>
            <div class="group-box">
              <div class="group-item">
                <el-button class="exam-base-info-button" type="primary" plain @click="saveBaseInfo">保存</el-button>
              </div>
            </div>
          </div>
        </div>
        <!-- 添加竞赛题目 -->
        <div class="exam-select-question-box">
          <el-button class="exam-add-question" :icon="Plus" type="text" @click="addQuestion()">
            添加题目
          </el-button>
          <el-table height="300px" :data="formExam.examQuestionList" class="question-select-list">
            <el-table-column prop="questionId" width="180px" label="题目id" />
            <el-table-column prop="title" :show-overflow-tooltip="true" label="题目标题" />
            <el-table-column prop="difficulty" width="80px" label="题目难度">
              <template #default="{ row }">
                <div v-if="row.difficulty === 0" style="color:#3EC8FF;">简单</div>
                <div v-if="row.difficulty === 1" style="color:#FE7909;">中等</div>
                <div v-if="row.difficulty === 2" style="color:#FD4C40;">困难</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80px">
              <template #default="{ row }">
                <el-button circle type="text" @click="deleteExamQuestion(formExam.examId, row.questionId)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 题目配置模块 题目列表勾选加序号 -->
        <div>
          <el-dialog v-model="dialogVisible">
            <div class="exam-list-box">
              <div class="exam-list-title required">选择竞赛题目</div>
              <el-form inline="true">
                <el-form-item label="题目难度">
                  <selector v-model="params.difficulty" style="width: 120px;"></selector>
                </el-form-item>
                <el-form-item label="题目名称">
                  <el-input v-model="params.title" placeholder="请您输入要搜索的题目标题" />
                </el-form-item>
                <el-form-item>
                  <el-button @click="onSearch" plain>搜索</el-button>
                  <el-button @click="onReset" plain type="info">重置</el-button>
                </el-form-item>
  
              </el-form>
              <!-- 题目列表 -->
              <el-table :data="questionList" @select="handleRowSelect" @select-all="handleSelectAll" row-key="questionId" ref="questionTableRef">
                <el-table-column type="selection" :reserve-selection="true"></el-table-column>
                <el-table-column prop="questionId" label="题目id">
                    <template #header>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <span>题目id</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="题目标题" />
                <el-table-column prop="difficulty" label="题目难度">
                    <template #default="{ row }">
                        <div v-if="row.difficulty === 0" style="color:#3EC8FF;">简单</div>
                        <div v-if="row.difficulty === 1" style="color:#FE7909;">中等</div>
                        <div v-if="row.difficulty === 2" style="color:#FD4C40;">困难</div>
                    </template>
                </el-table-column>
              </el-table>
              <!-- 分页区域 -->
              <div class="exam-question-list-button">
                <el-pagination background size="small" layout="total, sizes, prev, pager, next, jumper" :total="total"
                  v-model:current-page="params.pageNum" v-model:page-size="params.pageSize"
                  :page-sizes="[1, 5, 10, 15, 20]" @size-change="handleSizeChange"
                  @current-change="handleCurrentChange" />
                <el-button class="question-select-submit" type="primary" plain
                  @click="submitSelectQuestion">提交</el-button>
              </div>
            </div>
          </el-dialog>
        </div>
  
        <!-- 提交任务区域 -->
        <div class="submit-box absolute">
          <el-button type="info" plain @click="goBack">取消</el-button>
          <el-button type="primary" plain @click="publishExam">发布竞赛</el-button>
        </div>
      </div>
    </div>
  </template>
<script setup>
import { examAddService,addExamQuestionService,getExamDetailService,editExamService,delExamQuestionService,publishExamService } from "@/apis/exam"
import { getQuestionListService } from "@/apis/question"
import Selector from "@/components/QuestionSelector.vue"
import router from '@/router'
import { reactive, ref, onMounted } from "vue"
import { Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router';

const type = useRoute().query.type
const examId = useRoute().query.examId
const formExam = reactive({
  examId: '',
  title: '',
  examDate: '',
  examQuestionList: []
})

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  difficulty: '', // 确保可以设置为 0, 1, 或 2
  title: ''
})


// 返回
function goBack() {
  router.go(-1)
}

async function saveBaseInfo() {
  const fd = new FormData()
  for (let key in formExam) {
    if (key === 'examDate') {
      fd.append('startTime', formExam.examDate[0]);
      fd.append('endTime', formExam.examDate[1]);
    } else if (key !== 'startTime' && key !== 'endTime') {
      fd.append(key, formExam[key])
    }
  }
  if (formExam.examId) {
    //编辑
    await editExamService(fd)
  } else {
    const addRes = await examAddService(fd)
    formExam.examId = addRes.data
    // 更新URL中的examId
    router.replace({
      path: '/oj/layout/updateExam',
      query: { type: 'edit', examId: addRes.data }
    })
  }
  ElMessage.success('基本信息保存成功')
}

const questionList = ref([])
const total = ref(0)
async function getQuestionList() {
  const result = await getQuestionListService(params)
  console.log(result)
  questionList.value = result.rows
  total.value = result.total
  
  // 在数据加载完成后，设置已选中的题目
  setTimeout(() => {
    if (questionTableRef.value && questionList.value.length > 0 && questionIdSet.value.length > 0) {
      questionList.value.forEach(row => {
        if (questionIdSet.value.includes(row.questionId)) {
          questionTableRef.value.toggleRowSelection(row, true)
        }
      })
    }
  }, 100)
}

const dialogVisible = ref(false)
function addQuestion() {
  if (formExam.examId === null || formExam.examId === '') {
    ElMessage.error('请先保存竞赛基本信息')
  } else {
    // 先清空已选题目集合
    questionIdSet.value = []
    
    // 如果已有题目，将其ID添加到已选集合中
    if (formExam.examQuestionList && formExam.examQuestionList.length > 0) {
      formExam.examQuestionList.forEach(question => {
        questionIdSet.value.push(question.questionId)
      })
    }
    
    getQuestionList()
    dialogVisible.value = true
    
    // 在下一个DOM更新周期，设置表格选中行
    setTimeout(() => {
      if (questionTableRef.value && questionList.value.length > 0) {
        questionList.value.forEach(row => {
          if (questionIdSet.value.includes(row.questionId)) {
            questionTableRef.value.toggleRowSelection(row, true)
          }
        })
      }
    }, 300)
  }
}

function handleSizeChange() {
  params.pageNum = 1
  getQuestionList()
}

function handleCurrentChange() {
  getQuestionList()
}


function onSearch() {
  params.pageNum = 1
  getQuestionList()
}

function onReset() {
  params.pageNum = 1
  params.pageSize = 10
  params.title = ''
  params.difficulty = ''
  getQuestionList()
}

async function publishExam() {
  await publishExamService(formExam.examId)
  router.push("/oj/layout/exam")
}

const questionIdSet = ref([])
const questionTableRef = ref(null)

function handleSelectAll(selection) {
    if (selection.length > 0) {
        // 选中所有题目
        questionIdSet.value = questionList.value.map(item => item.questionId)
    } else {
        // 取消选中所有题目
        questionIdSet.value = []
    }
}

function handleRowSelect(selection) {
    questionIdSet.value = selection.map(item => item.questionId)
}

async function submitSelectQuestion() {
  const examQ = reactive({
    examId: formExam.examId,
    questionIdSet: questionIdSet.value
  })
  console.log(examQ)
  await addExamQuestionService(examQ);
  getExamDetailById(formExam.examId)
  dialogVisible.value = false
  ElMessage.success('竞赛题目添加成功')
}

// 页面加载时获取考试详情
onMounted(async () => {
  if (examId) {
    formExam.examId = examId
    await getExamDetailById(examId)
  }
})

async function getExamDetail() {
  const examId = useRoute().query.examId
  if (examId) {
    formExam.examId = examId
    getExamDetailById(examId)
  }
}
getExamDetail()

async function deleteExamQuestion(examId, questionId) {
  await delExamQuestionService(examId, questionId)
  getExamDetailById(examId)
  ElMessage.success('竞赛题目删除成功')
}

async function getExamDetailById(examId) {
  const examDetail = await getExamDetailService(examId)
  formExam.examQuestionList = []
  Object.assign(formExam, examDetail.data)
  formExam.examDate = [examDetail.data.startTime, examDetail.data.endTime]
}

// 修改全选功能
function selectAllQuestions() {
    if (questionList.value && questionList.value.length > 0) {
        // 获取当前页所有题目的ID
        const currentPageQuestionIds = questionList.value.map(item => item.questionId);
        // 更新已选题目集合
        questionIdSet.value = currentPageQuestionIds;
        // 选中当前页所有行
        questionList.value.forEach(row => {
            questionTableRef.value.toggleRowSelection(row, true);
        });
        // 立即提交选中的题目
        submitSelectQuestion();
    }
}

</script>

<style lang="scss" scoped>
.add-exam-component-box {
  height: 100%;
  overflow: hidden;
  position: relative;
  background: #f5f7fa;
}

.exam-list-box {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .question-select-submit {
    margin-top: 24px;
    width: 100%;
    height: 40px;
    font-size: 15px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }
  }

  .exam-list-title {
    font-size: 16px;
    color: #2c3e50;
    font-weight: 500;
    margin-bottom: 20px;
    position: relative;
    padding-left: 15px;

    &.required::before {
      position: absolute;
      content: '*';
      font-size: 18px;
      color: #f56c6c;
      left: 0;
      top: 2px;
    }
  }
}

.add-exam-component {
  width: 100%;
  background: transparent;
  padding: 24px;
  padding-bottom: 120px;
  overflow-y: auto;
  box-sizing: border-box;
  height: calc(100vh - 50px);

  .exam-select-question-box {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-top: 24px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .exam-add-question {
      font-size: 15px;
      margin-bottom: 16px;
      transition: all 0.3s ease;

      &:hover {
        color: #409eff;
        transform: translateY(-2px);
      }
    }

    .question-select-list {
      margin-bottom: 20px;
      border-radius: 4px;
      overflow: hidden;

      :deep(.el-table) {
        border-radius: 4px;
      }

      :deep(.el-table__row) {
        transition: all 0.3s ease;

        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }

  .exam-base-info-box {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .exam-base-title {
      padding: 16px 24px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .base-title {
        font-size: 18px;
        font-weight: 500;
        color: #2c3e50;
      }

      .go-back {
        color: #606266;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          color: #409eff;
        }
      }
    }

    .exam-base-info {
      padding: 24px;
    }
  }

  .group-box {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .group-item {
      display: flex;
      align-items: center;

      .exam-base-info-button {
        margin-left: 104px;
        width: 420px;
        height: 40px;
        font-size: 15px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
        }
      }

      .item-label {
        font-size: 15px;
        color: #2c3e50;
        width: 94px;
        position: relative;
        padding-left: 15px;

        &.required::before {
          position: absolute;
          content: '*';
          font-size: 18px;
          color: #f56c6c;
          left: 0;
          top: 0;
        }
      }
    }
  }

  .submit-box {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    padding: 24px;
    background: #fff;
    box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);

    &.absolute {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 999;
    }

    .el-button {
      min-width: 120px;
      height: 40px;
      font-size: 15px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    margin: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #ebeef5;
  }

  .el-dialog__body {
    padding: 24px;
  }
}

:deep(.el-table) {
  th.el-table__cell {
    background-color: #f5f7fa;
    color: #2c3e50;
    font-weight: 500;
  }
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 4px;
  }
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}
</style>

<style>
.w-e-text-container {
  min-height: 142px;
}
</style>